<script setup>
import { CircleCheck, User, Lock, Message, Key } from '@element-plus/icons-vue'
import { ref, watch, nextTick, onUnmounted } from 'vue'
import { useRegisterService, useLoginService, useGetUserIdService, useSendVerificationCode } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const userStore = useUserStore()
const router = useRouter()

// 标记是否登录
// true表示当前在登录页
// false表示当前在注册页
const isLogin = ref(false)
// 标记是否使用邮箱登录
// true表示使用邮箱登录
// false表示使用学号登录
const isMail = ref(false)
// 定义变量用来存储用户信息
const formModel = ref({
  studentId: '',
  email: '',
  code: '',  // 验证码
  password: '',
  repassword: '',
  // 选择的登陆方式
  loginType: isMail.value ? 'email_password' : 'studentId_password'
})
// 创建者id（即用户的注册id）
const userId = ref('')
// 定义变量用来获取dom元素->表单组件
const form = ref()
// 前端验证规则
const rules = {
  studentId: [
    // 非空验证
    { required: true, message: '请输入你的学号', trigger: 'blur' },
    // 长度验证
    { min: 1, max: 12, message: '请输入长度正确的学号', trigger: 'blur' }
  ],
  email: [
    // 非空验证
    { required: true, message: '请输入邮箱号', trigger: 'blur' },
    // 正则验证
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱号',
      trigger: 'blur'
    }
  ],
  code: [
    // 非空验证
    { required: true, message: '请输入验证码', trigger: 'blur' },
    // 长度验证
    { min: 6, max: 6, message: '请输入6位数字验证码', trigger: 'blur' }
  ],
  password: [
    // 非空验证
    { required: true, message: '请输入密码', trigger: 'blur' },
    // 长度验证
    { min: 6, max:12, message: '请输入6-12位密码', trigger: 'blur' } 
  ],
  repassword: [
    // 非空验证
    { required: true, message: '请确认密码', trigger: 'blur' },
    // 自定义验证
    {
      validator: (rule, value, callback) => {   
        if (value !== formModel.value.password) {       
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
// 注册点击事件
const register = async () => {
  // console.log(formModel.value)
  // 注册前预校验
  await form.value.validate()
  const res = await useRegisterService(formModel.value)
  if (res.data.status === 1) {
    ElMessage.error(res.data.message)
  } else {
    ElMessage.success('注册成功')
    isLogin.value = true
  }
}
// 登录点击事件
const login = async () => {
  // 登陆前预校验
  await form.value.validate()
  const res = await useLoginService(formModel.value)
  if (res.data.status === 1) {
    ElMessage.error(res.data.message)
  } else {
    // 登录成功
    // 调用接口拿到创建者id（即注册id）
    const idRes = await useGetUserIdService(formModel.value)
    if (idRes.data.status === 1) {
      return ElMessage.error(idRes.data.message)
    } else {
      ElMessage.success(idRes.data.message + idRes.data.userId)
    }
    userId.value = idRes.data.userId
    // pinia中存token、学号、创建者id（注册id）
    userStore.setToken(res.data.token)
    userStore.setStudentId(formModel.value.studentId)
    userStore.setUserId(userId.value)
    console.log('登录时，userStore.userId：' + userStore.userId + ',userStore.studentId:' + userStore.studentId)
    // 登陆成功，跳转到首页
    router.push('/')
    ElMessage.success('登录成功')
  }
}
// 切换登录/注册时清空表单数据
watch([isLogin, isMail], () => {
  formModel.value = {
    studentId: '',
    email: '',
    code: '',
    password: '',
    repassword: '',
    loginType: isMail.value ? 'email_password' : 'studentId_password'
  }
})
// 定义变量存储发送验证码间隔时间
const defaultSecond = 60  // 默认60s
const second = ref(defaultSecond)  // 倒计时
// 定时器id
let timeId = 0
// 判断发送验证码按钮是否禁用
// true为禁用
// false为不禁用
const isBtnDown = ref(false)
// 发送验证码事件
const sendCode = async () => {
  const res = await useSendVerificationCode(formModel.value)
  console.log(res)  
  if (res.data.status === 0) {
    ElMessage.success('验证码发送成功')
    // 开始倒计时
    timeId = setInterval(() => {
      // 禁用按钮
      isBtnDown.value = true
      second.value--
      if (second.value <= 0) {
        // 清除定时器
        clearInterval(timeId)
        // 归位
        second.value = defaultSecond
        isBtnDown.value = false
      }
    }, 1000)
  }
}
// 组件卸载前执行
onUnmounted(() => {
  if (timeId) {
    clearInterval(timeId)
  }
})
</script>

<template>
  <!-- 登录注册页面 -->
  <div class="index">
    <!-- 顶部内容盒子 -->
    <div class="top-wrapper">
      <!-- 网站名、网站图标 -->
      <div class="header-logo">
        <img src="../../assets/logo.ico" alt="">
        <!-- 实验室名 -->
        <span class="sitename">XiYouMobile</span>
      </div> 
    </div>
    <!-- 登陆注册内容盒子 -->
    <div class="login-Register">
      <!-- 登录内容盒子 -->
      <el-row class="login" v-if="isLogin" >
        <el-col :span="18" :offset="3" class="form">
          <!-- autocomplete="off"表示不自动填充表单 -->
          <el-form autocomplete="off" :model="formModel" :rules="rules" ref="form">
            <el-form-item>
              <h1 class="slogan">Welcome to 3G!</h1>
            </el-form-item>
            <!-- 学号密码登录 -->
            <div class="studentId-password-login"  v-if="!isMail">
              <el-form-item class="studentId" prop="studentId">
                <el-input v-model.trim="formModel.studentId" :prefix-icon="User" placeholder="请输入你的学号"/>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model.trim="formModel.password" type="password" :prefix-icon="Lock" placeholder="请输入你的密码"/>
              </el-form-item>
            </div>
            <!-- 邮箱验证码登录 -->
            <div class="email-code-login" v-if="isMail">
              <el-form-item class="studentId" prop="studentId">
                <el-input v-model.trim="formModel.studentId" :prefix-icon="User" placeholder="请输入你的学号"/>
              </el-form-item>
              <el-form-item class="mailbox" prop="email">
                <el-input v-model.trim="formModel.email" :prefix-icon="Message" placeholder="请输入你的邮箱"/>
              </el-form-item>
              <el-form-item prop="code">
                <el-input style="width: 140px;" v-model.trim="formModel.code" :prefix-icon="Key" placeholder="请输入验证码"/>
                <el-button style="width: 100px;" @click="sendCode" :disabled="isBtnDown">
                  {{ defaultSecond === second ? '发送验证码' : `${second}秒后重新发送` }}
                </el-button>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button @click="login" class="login-btn" type="primary" round>登录</el-button>
            </el-form-item>
          </el-form>
          <div class="login-way" @click="isMail = false" v-if="isMail">使用学号密码登录</div>
          <div class="login-way" @click="isMail = true" v-if="!isMail">忘记密码？使用邮箱验证码登录</div>
          <div class="toRegister" @click="isLogin=false">还未注册？点我注册</div>
        </el-col>
      </el-row>
      <!-- 注册内容盒子 -->
      <el-row class="register" v-else>
        <el-col :span="18" :offset="3" class="form">
          <!-- autocomplete="off"表示不自动填充表单 -->
          <el-form autocomplete="off" :model="formModel" :rules="rules" ref="form">
            <el-form-item>
              <h1 class="slogan">Welcome to 3G!</h1>
            </el-form-item>
            <el-form-item class="studentId" prop="studentId">
              <el-input v-model.trim="formModel.studentId" :prefix-icon="User" placeholder="请输入你的学号"/>
            </el-form-item>
            <el-form-item class="mailbox" prop="email">
              <el-input v-model.trim="formModel.email" :prefix-icon="Message" placeholder="请输入你的邮箱"/>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model.trim="formModel.password" type="password" :prefix-icon="Lock" placeholder="请输入你的密码"/>
            </el-form-item>
            <el-form-item prop="repassword">
              <el-input v-model.trim="formModel.repassword" type="password" :prefix-icon="Lock" placeholder="请确认你的密码"/>
            </el-form-item>
            <el-form-item>
              <el-button @click="register" class="register-btn" type="primary" round>注册</el-button>
            </el-form-item>
          </el-form>
          <div class="toLogin" @click="isLogin=true">已有账号？点我登录</div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.index {
  height: 100vh;
  width: 100%;

  // 顶部实验室名称
  .top-wrapper {
    display: flex;
    width: 100%;
    height: 12%;
    flex-direction: row;
    justify-content: space-between;

    .header-logo {
      display: flex;
      flex-grow: 0.25;
      align-items: center;
      justify-content: center;
      color: hsl(139, 50%, 43%);

      .sitename {
        margin-left: 10px;
        font-size: 20px;
        font-family: 'basteleur-E';
      }
    }
  }

  // 登陆注册页
  .login-Register {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 5vh;

    // 登录
    .login {
      width: 320px;
      height: 400px;

      .form {
        margin-top: 15%;

        .slogan {
          font-family: 'pixel-E';
        }

        .studentId {
          margin-top: 20%;
        }

        .login-btn {
          margin-top: 5%;
          width: 240px;
          border-radius: 3px;
        }
      }

      .login-way {
        margin: 15% 0 5%;
        text-align: center;
        font-size: 13px;
        cursor: pointer;
        color: #a5a3a3;
        text-decoration: underline;
      }

      .login-way:hover {
        color: rgb(89, 191, 202);
      }

      .toRegister {
        text-align: center;
        font-size: 13px;
        cursor: pointer;
        color: #a5a3a3;
        text-decoration: underline;
      }

      .toRegister:hover {
        color: rgb(89, 191, 202);
      }
    }

    // 注册
    .register {
      width: 320px;
      height: 470px;

      .form {
        margin-top: 15%;

        .slogan {
          font-family: 'pixel-E';
          color: rgb(0, 0, 0);
        }

        .studentId {
          margin-top: 20%;
        }

        .register-btn {
          margin-top: 5%;
          width: 240px;
          border-radius: 3px;
        }
      }

      .toLogin {
        margin-top: 15%;
        text-align: center;
        font-size: 13px;
        cursor: pointer;
        color: #a5a3a3;
        text-decoration: underline;
      }

      .toLogin:hover {
        color: rgb(89, 191, 202);
      }
    }
  }
}
</style>
